﻿using System;
using System.Linq;
using Evpo.ContactData.Common;
using Evpo.ContactData.Data;
using System.Collections.Generic;

namespace Evpo.ContactData.ViewModel
{
    public abstract class ContactViewModel
    {
        public ContactViewModel(ModelFactory factory, IConnection conn)
        {
            _relAdapter = factory.CreateRelationshipAdapter(conn);
            _factory = factory;
            _contactAdapter = factory.CreateContactAdapter(conn);
            _titleAdapter = factory.CreateTitleAdapter(conn);
        }

        #region Fields
        protected readonly ContactAdapter _contactAdapter;
        protected readonly TitleAdapter _titleAdapter;
        protected readonly RelationshipAdapter _relAdapter;
        protected readonly ModelFactory _factory;
        #endregion

        #region Properties
        #endregion

        #region Methods

        public ContactListItem BlankContactListItem()
        {
            return new ContactListItem()
            {
                Contact = _factory.CreateContact(),
            };
        }

        public ContactListItem LoadContactListItem(int contactID)
        {
            Contact contact = _contactAdapter.Load(contactID);
            DictionaryItem title = _titleAdapter.GetItem(contact.TitleID);

            return new ContactListItem()
            {
                Contact = contact,
                TitleName = title.Name,
            };
        }


        public List<ContactLink> ContactLinks(int contactID)
        {
            return (from relInfo in _relAdapter.Relationships(contactID)
                    select new ContactLink()
                    {
                        ContactListItem = new ContactListItem()
                        {
                            Contact = relInfo.Contact,
                            TitleName = relInfo.TitleName,
                        },
                        TypeName = relInfo.TypeName,
                    }).ToList();
        }

        #endregion Methods
    }
}
